import tkinter as tk
from tkinter import messagebox, ttk, filedialog
from tkinter import Toplevel

class TkWin:
    def __init__(self, master):
        self.master = master
        self.master.withdraw()
        self.table_window = None

    def select_file(self):
        file_path = filedialog.askopenfilename(title="选择一个xlsx文件", filetypes=[("Excel Files", "*.xlsx")])
        return file_path

    def show_info(self, title, message):
        messagebox.showinfo(title, message)

    def show_warning(self, title, message):
        messagebox.showwarning(title, message)

    def show_error(self, title, message):
        messagebox.showerror(title, message)

    def ask_question(self, title, message):
        return messagebox.askyesno(title, message)

    def show_table(self, list_data, callback=None):
        # 创建一个新窗口
        self.table_window = Toplevel(self.master)
        self.table_window.title("表格")

        # 创建表格
        tree = ttk.Treeview(self.table_window, columns=('名称', '价格', '佣金', '介绍', '电图片地址'), show='headings')
        tree.heading('名称', text='名称')
        tree.heading('价格', text='价格')
        tree.heading('佣金', text='佣金')
        tree.heading('介绍', text='介绍')
        tree.heading('电图片地址', text='电图片地址')

        # 插入数据
        for item in list_data:
            tree.insert('', 'end', values=item)

        # 放置表格
        tree.pack()

        # 添加关闭按钮
        close_button = tk.Button(self.table_window, text="关闭", command=self.close_table)
        close_button.pack(side=tk.LEFT)

        # 添加确认按钮
        confirm_button = tk.Button(self.table_window, text="确认", command=lambda: self.confirm_action(callback))
        confirm_button.pack(side=tk.RIGHT)
        self.master.mainloop()
        # 返回窗口对象，以便外部可以调用窗口的方法
        return self.table_window

    def close_table(self):
        # 关闭窗口
        if self.table_window:
            self.table_window.destroy()

    def confirm_action(self, callback):
        # 确认操作
        if self.table_window:
            if callback:
                callback(True)
            self.close_table()